import smtplib
import time
from email.message import Message
from time import sleep
import email.utils
import base64
from tornado_smtp.client import TornadoSMTP
from tornado.ioloop import IOLoop
from handlers.base import Mqtonado
import settings


def send_mail():
    smtpserver = 'smtp.microembed.net'
    username = 'dev@microembed.net'
    password = 'Iot12345'

    from_addr = 'noreply@microembed.net'
    to_addr = 'zhoujiexiong@dingtalk.com'
    # cc_addr = 'ccccccccc@qq.com'

    t = email.utils.formatdate(time.time(), True)

    message = Message()
    message['Subject'] = 'Mail Subject 2'
    message['From'] = from_addr
    message['To'] = to_addr
    # message['Cc'] = cc_addr
    # message.set_payload('mail content '+time)
    msg = message.as_string()

    # sm = smtplib.SMTP(smtpserver,port=587,timeout=20)
    sm = smtplib.SMTP(smtpserver, port=25, timeout=20)
    sm.set_debuglevel(1)
    sm.ehlo()
    # sm.starttls()
    sm.ehlo()

    sm.login(username, password)
    sm.sendmail(from_addr, to_addr, msg)
    sleep(5)
    sm.quit()


def on_message(client, userdata, topic, payload):
    print '%s: %s' % (topic, payload)


def main():
    client = Mqtonado(on_message, None)
    # TODO: query host address from ZK service
    client.connect(settings.MQ_HOST, username=settings.MQ_USER, password=settings.MQ_PASS)
    client.subscribe('send_mail_topic')
    IOLoop.current().start()


if '__main__' == __name__:
    main()
